import React, { Component } from "react";
import { View, Image, ActivityIndicator } from "react-native";
import { equals } from "solomon-utils-rn";

class ImgWithLoading extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
    };
  }

  shouldComponentUpdate = (nextProps, nextState) => {
    const { style, source, loadingStyle } = this.props;
    const {
      style: styleNext,
      source: sourceNext,
      loadingStyle: loadingStyleNext,
    } = nextProps;
    const { loading } = this.state;
    const { loading: loadingNext } = nextState;
    if (
      !equals(style, styleNext) ||
      !equals(source, sourceNext) ||
      !equals(loadingStyle, loadingStyleNext) ||
      loading !== loadingNext
    ) {
      return true;
    } else {
      return false;
    }
  };

  onLoadStart = () => {
    this.setState({
      loading: true,
    });
  };

  onLoadEnd = () => {
    const { loadEnd } = this.props;
    this.setState({
      loading: false,
    });

    if (typeof loadEnd === "function") {
      loadEnd();
    }
  };

  render() {
    const { loading } = this.state;
    const {
      style, // img样式
      source, // img数据源
      // loadingStyle, // loading样式，主要用于居中定位
    } = this.props;
    return (
      <View>
        <Image
          style={style}
          source={source}
          onLoadStart={this.onLoadStart}
          onLoadEnd={this.onLoadEnd}
        />
        {loading ? (
          <ActivityIndicator
            style={{
              position: "absolute",
              width: "100%",
              height: "100%",
              justifyContent: "center",
              alignItems: "center",
            }}
          />
        ) : null}
      </View>
    );
  }
}

export default ImgWithLoading;
